package sdk.webview.fmc.com.fmcsdk.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebIconDatabase;
import com.tencent.smtt.sdk.WebStorage;

import java.util.List;

import javax.net.ssl.SSLHandshakeException;

import cn.jpush.android.api.JPushInterface;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.bean.AgreementBean;
import sdk.webview.fmc.com.fmcsdk.bean.ErrorEvnet;
import sdk.webview.fmc.com.fmcsdk.bean.SysSettingsInfoBean;
import sdk.webview.fmc.com.fmcsdk.check.activity.CheckDetailsActivity;
import sdk.webview.fmc.com.fmcsdk.db.DBManager;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.interfaces.LoginView;
import sdk.webview.fmc.com.fmcsdk.interfaces.OnDialogSureListener;
import sdk.webview.fmc.com.fmcsdk.manager.FMSdk;
import sdk.webview.fmc.com.fmcsdk.presenter.LoginPresenter;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DialogUtils;
import sdk.webview.fmc.com.fmcsdk.util.Language;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.SSLAgent;
import sdk.webview.fmc.com.fmcsdk.util.SharedPrefUtils;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBusSubscriber;
import sdk.webview.fmc.com.fmcsdk.view.ChangePasswordDialog;
import sdk.webview.fmc.com.fmcsdk.view.EditPwdDialog;
import sdk.webview.fmc.com.fmcsdk.view.HookCheckBox;
import sdk.webview.fmc.com.fmcsdk.view.LoginBottomDialog;
import sdk.webview.fmc.com.fmcsdk.view.NetWorkImageView;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity<LoginView, LoginPresenter> implements LoginView, View.OnClickListener {
    private String PWD_FORGET = "1", IS_OPEN_REMEMBER_PASSWORD = "1";
    EditText username_view;
    EditText password_view;
    Button login_btn, login_btn_sso;
    TextView changeconnect_view, tv_zh_cn, tv_zh_cht, tv_en_us, tv_forget_pwd;
    ImageView ivDeleteUsername, ivEamlogo;
    ImageView ivDeletePassword;
    HookCheckBox hook_checkbox, hook_checkbox_xie;
    RelativeLayout rlBj;
    private LoginBottomDialog loginBottomDialog;
    private LinearLayout ll_check_xieyi;

    private LinearLayout ll_login_way_layout, ll_login_way;
    private ImageView iv_way;
    private TextView tv_way;

    private RelativeLayout rl_sms_code, rl_phone, rl_username, rl_password;
    private EditText login_sms_code, login_phone;
    private TextView tv_send_sms;

    private int loginWay = 1;  //登录的方式 1: 账号密码登录   2：手机验证码登录
    private String mPattern;

    //Manifest.permission.CAMERA,
    private String[] permissionsLocation = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private String[] permissionsStore = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String[] permissionsInternet = {Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET
    };
    private LinearLayout ll_check;
    private TextView tv_xieyi, tv_remember_password;
    private AgreementBean agreementBean;
    private NetWorkImageView codeImage;
    private EditText etLoginCode;
    private String appName;
    private LinearLayout llLoginLang, ll_remember_password;
    private boolean isApplyPermissions;
    public boolean isSys = false;

    private String xieyiStr;//隐私协议地址
    private boolean isHasXieyiAddr = false; //是否有隐私协议地址 ，默认没有

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

//        try {
//            SM2Utils.main();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Log.e("shuchang", " context.getPackageName()---->" + context.getPackageName());

        appName = (String) Utility.getMetaData(this, Constant.APP_NAME);

        //国贸云固定的baseURL https://gmy.itcpm.com/
        if (TextUtils.isEmpty(sharedPrefs.getString(Constant.BASE_ADDRESS_URL, ""))) {
            if (Constant.APP_NAME_GMY.equals(appName)) {
                sharedPrefs.edit().putString(Constant.BASE_ADDRESS_URL, "https://gmy.itcpm.com").commit();
            }
        }
        username_view = (EditText) findViewById(R.id.login_username);
        password_view = (EditText) findViewById(R.id.login_password);
        login_btn = (Button) findViewById(R.id.login_btn);
        login_btn_sso = (Button) findViewById(R.id.login_btn_sso);
        changeconnect_view = (TextView) findViewById(R.id.login_changeconnect);
        ivDeleteUsername = (ImageView) findViewById(R.id.iv_delete_username);
        ivDeletePassword = (ImageView) findViewById(R.id.iv_delete_password);
        llLoginLang = (LinearLayout) findViewById(R.id.ll_login_lang);
        rlBj = (RelativeLayout) findViewById(R.id.rl_bj);
        tv_zh_cn = (TextView) findViewById(R.id.tv_zh_cn);
        tv_zh_cht = (TextView) findViewById(R.id.tv_zh_cht);
        tv_en_us = (TextView) findViewById(R.id.tv_en_us);
        tv_forget_pwd = (TextView) findViewById(R.id.tv_forget_pwd);
        codeImage = (NetWorkImageView) findViewById(R.id.web_framlayout);
        etLoginCode = (EditText) findViewById(R.id.login_code);
        ivEamlogo = (ImageView) findViewById(R.id.iv_eam_logo);

        ll_login_way_layout = (LinearLayout) findViewById(R.id.ll_login_way_layout);
        ll_login_way = (LinearLayout) findViewById(R.id.ll_login_way);
        iv_way = (ImageView) findViewById(R.id.iv_way);
        tv_way = (TextView) findViewById(R.id.tv_way);
        hook_checkbox = findViewById(R.id.hook_checkbox);
        hook_checkbox_xie = findViewById(R.id.hook_checkbox_xie);
        rl_sms_code = (RelativeLayout) findViewById(R.id.rl_sms_code);
        login_sms_code = (EditText) findViewById(R.id.login_sms_code);
        login_phone = (EditText) findViewById(R.id.login_phone);
        tv_send_sms = (TextView) findViewById(R.id.tv_send_sms);

        rl_phone = (RelativeLayout) findViewById(R.id.rl_phone);
        rl_username = (RelativeLayout) findViewById(R.id.rl_username);
        rl_password = (RelativeLayout) findViewById(R.id.rl_password);
        tv_remember_password = (TextView) findViewById(R.id.tv_remember_password);


        ll_login_way.setOnClickListener(this);
        tv_send_sms.setOnClickListener(this);


        tv_zh_cn.setOnClickListener(this);
        tv_zh_cht.setOnClickListener(this);
        tv_en_us.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        login_btn_sso.setOnClickListener(this);
        changeconnect_view.setOnClickListener(this);
        ivDeleteUsername.setOnClickListener(this);
        ivDeletePassword.setOnClickListener(this);
        codeImage.setOnClickListener(this);
        tv_forget_pwd.setOnClickListener(this);
        setTextChangedListener();
        //设置默认用户名
        username_view.setText(sharedPrefs.getString(Constant.LOGIN_NAME, ""));
        username_view.setSelection(getText(username_view).length());
        ll_check_xieyi = (LinearLayout) findViewById(R.id.ll_check_xieyi);
        ll_check = (LinearLayout) findViewById(R.id.ll_checkbox);
        tv_xieyi = (TextView) findViewById(R.id.tv_xieyi);
        tv_xieyi.setOnClickListener(this);
        ll_remember_password = (LinearLayout) findViewById(R.id.ll_remember_password);
        ll_remember_password.setOnClickListener(this);
        boolean remember_password = PreferencesHelper.getBooleanData("remember_password");
        hook_checkbox.setCheck(remember_password);

        //如果卸载了重装，第一次打开了APP的情况下极光仍在服务的时候要将其关闭掉
        boolean pushStopped = JPushInterface.isPushStopped(context.getApplicationContext());
        if (!pushStopped) {
            JPushInterface.stopPush(this);
        }
//        new JpushUtils().startPush(getApplicationContext());
//        JCollectionAuth.setAuth(context, true); //如初始化被拦截过，将重试初始化过程

        if (Constant.APP_NAME_GMY.equals(appName) || Constant.APP_NAME_FMS.equals(appName)) {
            ll_check.setVisibility(View.VISIBLE);
            isHasXieyiAddr = true;
        } else {
            isHasXieyiAddr = false;
            ll_check.setVisibility(View.GONE);
            setAgreement();
        }

        if (remember_password) {
            String user_password = PreferencesHelper.getData("user_password");
            if (!TextUtils.isEmpty(user_password)) {
                password_view.setText(user_password);
            } else {
                password_view.setText("");
            }
        }
        //领展添加微软单点登录
        if (Constant.APP_NAME_LINK.equals(appName) || Constant.APP_NAME_EAM.equals(appName)) {
            login_btn_sso.setVisibility(View.VISIBLE);
            llLoginLang.setVisibility(View.VISIBLE);
            if (Constant.APP_NAME_EAM.equals(appName)) {
                login_btn_sso.setText(getResources().getString(R.string.eam_login));
                ivEamlogo.setVisibility(View.VISIBLE);
            }
        } else if (Constant.APP_NAME_FMS.equals(appName)) {
            llLoginLang.setVisibility(View.VISIBLE);
        }


        if (Constant.APP_NAME_ZTE.equals(appName)) {
            RxBus.getDefault().toObservable(ErrorEvnet.class).subscribe(new RxBusSubscriber<ErrorEvnet>() {
                @Override
                public void receive(ErrorEvnet data) {
                    String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
                    if (!TextUtils.isEmpty(address)) {
                        codeImage.setImageURL(address + "/uc/captcha/getCaptcha?captchaKey=" + presenter.captchaKey + "&time=" + System.currentTimeMillis());
                    }

                }
            });
        }

        SSLAgent.getInstance().trustAllHttpsCertificates();

        if (appName.equals(Constant.APP_NAME_XIYOU)) {
            presenter.getXiYouSSOSetting();
        }

        if (sharedPrefs.getInt("lang", 0) == 0) {
            setLanguageColor(tv_zh_cn);
        } else if (sharedPrefs.getInt("lang", 0) == 1) {
            setLanguageColor(tv_en_us);
        } else if (sharedPrefs.getInt("lang", 0) == 2) {
            setLanguageColor(tv_zh_cht);
        }


        RxBus.getDefault().toObservable(ErrorEvnet.class).subscribe(new RxBusSubscriber<ErrorEvnet>() {
            @Override
            public void receive(ErrorEvnet data) {
                if (getResources().getString(R.string.get_sms).equals(tv_send_sms.getText().toString().trim())) {
                    Log.e("shuchang", "tv_send_sms--恢复可点击");
                    tv_send_sms.setEnabled(true);
                    tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
                }
            }
        });


        hook_checkbox.setOnCheckChangeListener(new HookCheckBox.OnCheckChangeListener() {
            @Override
            public void onCheckChange(boolean isCheck) {
                boolean remember_password = PreferencesHelper.getBooleanData("remember_password");
                remember_password = !remember_password;
                PreferencesHelper.saveBooleanData("remember_password", remember_password);
            }
        });
        hook_checkbox_xie.setOnCheckChangeListener(new HookCheckBox.OnCheckChangeListener() {
            @Override
            public void onCheckChange(boolean isCheck) {

            }
        });


    }

    private void setAgreement() {
        agreementBean = PreferencesHelper.getData(AgreementBean.class);
        if (agreementBean != null) {
            if (TextUtils.isEmpty(agreementBean.getContent())) {
                ll_check.setVisibility(View.GONE);
                return;
            } else {
                ll_check.setVisibility(View.VISIBLE);
            }
        }

        if (!isHasXieyiAddr) {
            tv_xieyi.getPaint().setFlags(0); //下划线
            if (agreementBean != null) {
                ll_check.setVisibility(View.VISIBLE);
                if (sharedPrefs.getInt("lang", 0) == 2) {
                    tv_xieyi.setText("《" + agreementBean.getTitle_ch() + "》");
                } else if (sharedPrefs.getInt("lang", 0) == 1) {
                    tv_xieyi.setText("\"" + agreementBean.getTitle_en() + "\"");
                    tv_xieyi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                    tv_xieyi.getPaint().setAntiAlias(true);//抗锯齿
                } else {
                    tv_xieyi.setText("《" + agreementBean.getTitle() + "》");
                }
                tv_xieyi.setOnClickListener(this);


                if (appName.equals(Constant.APP_NAME_XIYOU)) {
                    tv_xieyi.setTextColor(getResources().getColor(R.color.color_text_xieyi2));
                } else {
                    tv_xieyi.setTextColor(getResources().getColor(R.color.color_text_xieyi));
                }

//                if (agreementBean.getIsCustom() == 2) {
//
//                    checkbox_xieyi.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            if (!is_check_xieyi) {
//                                checkbox_xieyi.setImageResource(R.drawable.check2);
//                                is_check_xieyi = true;
//                            } else {
//                                is_check_xieyi = false;
//                                checkbox_xieyi.setImageResource(R.drawable.checkbox_a7a7a7);
//                            }
//                        }
//                    });
//
//                }
            }
        }
//


//        checkbox_xieyi.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (!is_check_xieyi) {
//                    checkbox_xieyi.setImageResource(R.drawable.check2);
//                    is_check_xieyi = true;
//                } else {
//                    is_check_xieyi = false;
//                    checkbox_xieyi.setImageResource(R.drawable.checkbox_a7a7a7);
//                }
//            }
//        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        // clearX5Cache();
        String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
        if (!TextUtils.isEmpty(address)) {
            presenter.getAgreement();
            //中兴添加登录验证码验证
            if (Constant.APP_NAME_ZTE.equals(appName) && !isApplyPermissions) {
                RelativeLayout rlCode = (RelativeLayout) findViewById(R.id.rl_code);

                rlCode.setVisibility(View.VISIBLE);
                presenter.getRandomUUID();
                codeImage.setImageURL(address + "/uc/captcha/getCaptcha?captchaKey=" + presenter.captchaKey + "&time=" + System.currentTimeMillis());

            }

            PreferencesHelper.saveData("isOkGetSysInfo", "false");
            presenter.sysSettingsInfo();
            isSys = true;
        }
    }

    /**
     * 文字改变监听
     */
    private void setTextChangedListener() {
        //用户名
        username_view.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果输入了文字就显示删除的按钮
                if (s.toString().trim().length() > 0) {
                    ivDeleteUsername.setVisibility(View.VISIBLE);
                } else {
                    ivDeleteUsername.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        //密码
        password_view.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果输入了文字就显示删除的按钮
                if (s.toString().trim().length() > 0) {
                    ivDeletePassword.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePassword.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_btn) {
            Constant.isSll = true;
            if (needIgnoreClick(v)) {
                return;
            }

            //是否为领展单点登录
            sharedPrefs.edit().putBoolean(Constant.IS_LINK_OSS_LOGIN, false).apply();

            /**记录用户名，不管登录是否成功或者注销，都记住*/
//            sharedPrefs.edit().putString(Constant.LOGIN_NAME, getText(username_view)).apply();

            String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
            if (TextUtils.isEmpty(address)) {
                showConnectDialog(context.getString(R.string.need_input_connect_address));
                return;
            }
            if (loginWay == 1) {
                if (TextUtils.isEmpty(getText(username_view))) {
                    ToastMessage(getResources().getString(R.string.msg_login_usernameisnull));
                    return;
                }
                if (TextUtils.isEmpty(getText(password_view))) {
                    ToastMessage(getResources().getString(R.string.msg_login_psdisnull));
                    return;
                }
            } else if (loginWay == 2) {
                if (TextUtils.isEmpty(getText(login_phone))) {
                    ToastMessage(getResources().getString(R.string.msg_login_phoneisnull));
                    return;
                }
                if (TextUtils.isEmpty(getText(login_sms_code))) {
                    ToastMessage(getResources().getString(R.string.msg_login_codeisnull));
                    return;
                }
            }

            if (ll_check.getVisibility() == View.VISIBLE) {
                if (!hook_checkbox_xie.isCheck()) {
                    ToastMessage(getResources().getString(R.string.read_agreement));
                    return;
                }
            }

            //18126289365用户的注销
            boolean zhuxiao = sharedPrefs.getBoolean("zhuxiao", false);
            if (zhuxiao) {
                if ("18126289365".equals(getText(username_view))) {
                    ToastMessage("用户名或密码错误");
                    return;
                }
            }


            if (Constant.APP_NAME_ZTE.equals(appName)) {
                if (TextUtils.isEmpty(getText(etLoginCode))) {
                    ToastMessage(getResources().getString(R.string.msg_login_codeisnull));
                    return;
                }

            }


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //动态申请权限
                applyPermissions(0);

            } else {
                loginApp();
            }

        } else if (v.getId() == R.id.login_btn_sso) {
            Constant.isSll = true;
            sharedPrefs.edit().putBoolean(Constant.IS_LINK_OSS_LOGIN, true).apply();

            String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
            if (TextUtils.isEmpty(address)) {
                showConnectDialog(context.getString(R.string.need_input_connect_address));
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //动态申请权限
                applyPermissions(1);
            } else {

                Intent intent = new Intent();
                intent.setClass(context, LinkWebActivity.class);
                startActivityForResult(intent, 9784);
            }
        } else if (v.getId() == R.id.login_changeconnect) {
            showHttpIP(context.getString(R.string.need_input_connect_address));
        } else if (v.getId() == R.id.iv_delete_username) {
            username_view.setText("");
            ivDeleteUsername.setVisibility(View.GONE);
        } else if (v.getId() == R.id.iv_delete_password) {
            password_view.setText("");
            ivDeletePassword.setVisibility(View.GONE);
        } else if (v.getId() == R.id.tv_xieyi) {
            loginCount = false;

            if (isHasXieyiAddr) {
                Intent intent = new Intent(LoginActivity.this, CommonWebActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(LoginActivity.this, AgreementActivity.class);
                intent.putExtra("agreement_flag", 0);
                startActivity(intent);
            }

        } else if (v.getId() == R.id.tv_zh_cn) {
            setLang = 1;
            sharedPrefs.edit().putInt("lang", 0).apply();
            sharedPrefs.edit().putString("lang_code", getResources().getStringArray(R.array.multi_language_code)[0]).apply();
            setLanguageColor(tv_zh_cn);
            finish();
            Utility.startLoginActivityOrClearData(context);
        } else if (v.getId() == R.id.tv_zh_cht) {
            setLang = 1;
            sharedPrefs.edit().putInt("lang", 2).apply();
            sharedPrefs.edit().putString("lang_code", getResources().getStringArray(R.array.multi_language_code)[2]).apply();
            setLanguageColor(tv_zh_cht);
            finish();
            Utility.startLoginActivityOrClearData(context);
        } else if (v.getId() == R.id.tv_en_us) {
            setLang = 1;
            sharedPrefs.edit().putInt("lang", 1).apply();
            sharedPrefs.edit().putString("lang_code", getResources().getStringArray(R.array.multi_language_code)[1]).apply();
            setLanguageColor(tv_en_us);
            finish();
            Utility.startLoginActivityOrClearData(context);
        } else if (v.getId() == R.id.web_framlayout) {
            String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
            codeImage.setImageURL(address + "/uc/captcha/getCaptcha?captchaKey=" + presenter.captchaKey + "&time=" + System.currentTimeMillis());
            ;
        } else if (v.getId() == R.id.tv_forget_pwd) {   // 忘记密码
            Intent fpIntent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
            startActivity(fpIntent);
        } else if (v.getId() == R.id.ll_login_way) {  //  更换登录方式
            if (loginWay == 1) {  //从 账号密码 换成 短信
                loginWay = 2;

                rl_password.setVisibility(View.GONE);
                rl_username.setVisibility(View.GONE);
                ll_remember_password.setVisibility(View.GONE);

                rl_phone.setVisibility(View.VISIBLE);
                rl_sms_code.setVisibility(View.VISIBLE);

                iv_way.setImageResource(R.mipmap.img_zhanghu_login);
                tv_way.setText(getResources().getString(R.string.zhanghao_login));

            } else if (loginWay == 2) {
                loginWay = 1;

                rl_password.setVisibility(View.VISIBLE);
                rl_username.setVisibility(View.VISIBLE);
                ll_remember_password.setVisibility(View.VISIBLE);

                rl_phone.setVisibility(View.GONE);
                rl_sms_code.setVisibility(View.GONE);

                if ("0".equals(IS_OPEN_REMEMBER_PASSWORD)) {
                    password_view.setText("");
                    hook_checkbox.setVisibility(View.GONE);
                    tv_remember_password.setVisibility(View.GONE);
                } else {
                    hook_checkbox.setVisibility(View.VISIBLE);
                    tv_remember_password.setVisibility(View.VISIBLE);
                }

                iv_way.setImageResource(R.mipmap.img_sms_login);
                tv_way.setText(getResources().getString(R.string.duanxin_login));
            }

        } else if (v.getId() == R.id.tv_send_sms) {   //登录验证码登录 发送验证码
            String phoneStr = login_phone.getText().toString().trim();
            if (TextUtils.isEmpty(phoneStr)) {
                ToastUtils.showShort(context, getResources().getString(R.string.msg_login_phoneisnull));
                return;
            }
            if (!needIgnoreClick(v)) {
//                tv_send_sms.setEnabled(false); // 禁用按钮防止重复点击
//                tv_send_sms.setTextColor(getResources().getColor(R.color.has_send_sms));
                presenter.sendMessage(AESUtil.encryptAESExpand(phoneStr));//
            }

        }

    }

    @Override
    public void sendSmsSuccess() {
        startDaojishi();
    }

    @Override
    public void sendSmsFail() {
        tv_send_sms.setEnabled(true);
        tv_send_sms.setText(getResources().getString(R.string.get_sms));
        tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
    }

    private boolean isOld;

    @Override
    public void sysSettingsInfoFaiture() {
        isOld = true;
    }

    @Override
    public void sysSettingsInfoSucess() {
        isOld = false;
    }


    private void startDaojishi() {
        startCountDownTimer(60000, 1000); // 倒计时60秒
        tv_send_sms.setEnabled(false); // 禁用按钮防止重复点击
        tv_send_sms.setTextColor(getResources().getColor(R.color.has_send_sms));
    }

    private void updateLgWayUi(int way) {

    }

    private void setLanguageColor(View view) {

        tv_zh_cn.setSelected(false);
        tv_en_us.setSelected(false);
        tv_zh_cht.setSelected(false);
        view.setSelected(true);
        Language.switchLanguage(context, Language.getLocal(sharedPrefs.getInt("lang", 0)));

    }


    private String autiType = "1";

    private void loginApp() {
        presenter.codeStr = etLoginCode.getText().toString().trim();
        if (!(Constant.APP_NAME_FMS.equals(appName) || Constant.APP_NAME_GMY.equals(appName))) {
            if (ll_check.getVisibility() == View.VISIBLE) {
                if (agreementBean == null) {
                    //  ToastMessage(R.string.network_error);
                    if (DialogUtils.dialogSSL) {
                        if (Constant.isSll) {
                            Constant.isSll = false;
                            DialogUtils.insertDialog().dialogCenterComm(context, context.getString(R.string.kindly_reminder),
                                    context.getString(R.string.sslguoqi), true, new OnDialogSureListener() {
                                        @Override
                                        public void onDialogSureListener() {
                                        }
                                    });
                        }
                    } else {
                        ToastMessage(R.string.network_error);
                    }
                    return;
                }
            }
        }
        if (loginWay == 1) {
            autiType = "1";
        } else {
            autiType = "19";
        }
        //(加密前字符串示例：13971133023&123498
        String phoneCode = AESUtil.encryptAESExpand("13971133023" + "&" + getText(login_sms_code));
        if (agreementBean == null) {
            String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
            if (!TextUtils.isEmpty(address)) {
                presenter.getAgreement(1);
                // ToastUtils.showShort(this, getResources().getString(R.string.network_error));
            }
            return;
        }
        if (TextUtils.equals(agreementBean.getIsCustom(), "2")) {
            if (ll_check.getVisibility() == View.VISIBLE) {
                if (!hook_checkbox_xie.isCheck()) {
                    ToastMessage(getResources().getString(R.string.read_agreement));
                    return;
                }
            }

            FMSdk.init(this);

            checkPwd();
        } else {
            if (ll_check.getVisibility() == View.VISIBLE) {
                if (!hook_checkbox_xie.isCheck()) {
                    ToastMessage(getResources().getString(R.string.read_agreement));
                    return;
                }
            }

            FMSdk.init(this);
            checkPwd();
            //这里要判断跟当前的版本号是否一致
        }
    }

    private void checkPwd() {
        if (loginWay == 1) {
            presenter.checkBuUnamepwd(getText(username_view), getText(password_view), "");
        } else {
//            presenter.checkBuUnamepwd("", "", getText(login_phone));
            String phonecode = getText(login_phone) + "&" + getText(login_sms_code);
            presenter.login("", "", autiType, AESUtil.encryptAESExpand(phonecode));
        }
    }

    EditPwdDialog editPwdDialog;

    private void showEditPwdDialog(String code, String username, final String type) {
        if (isOld) {
            //修改密码的dialog
            final ChangePasswordDialog changePasswordDialog = new ChangePasswordDialog(this);
            changePasswordDialog.show();
            changePasswordDialog.setClicklistener(new ChangePasswordDialog.ClickListenerInterface() {
                @Override
                public void doConfirm(String initialPassword, String newPassword, String againPassword) {
                    //修改密码接口
                    String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
                    if (Constant.APP_NAME_ZSJ.equals(appName)) {
                        //修改密码接口
                        presenter.getSM2Key(initialPassword, newPassword, againPassword);
                    } else {
                        //修改密码接口
                        presenter.modifyPassword(initialPassword, newPassword, againPassword);
                    }
                    changePasswordDialog.dismiss();
                }

                @Override
                public void doCancel() {
                    changePasswordDialog.dismiss();
                }
            });
        } else {

            if (editPwdDialog != null) {
                editPwdDialog.dismiss();
            }
            editPwdDialog = new EditPwdDialog(LoginActivity.this, code, username,
                    new EditPwdDialog.ClickiInterface() {
                        @Override
                        public void clickSure(String username, String loginOldPwd, String loginNewPwd) {
                            presenter.editPwd(username, loginOldPwd, loginNewPwd, type);
                        }

                        @Override
                        public void clickCancel(String pwdChangeDec) {
                            if ("PWD_WILL_EXPIRE".equals(pwdChangeDec)) {  //继续
                                presenter.login(getText(username_view), getText(password_view), autiType, "");
                            } else {
                                login_sms_code.setText("");
                                password_view.setText("");
                            }
                            editPwdDialog.dismiss();

                        }
                    });

            editPwdDialog.show();
            editPwdDialog.setType("1");
        }
    }

    Snackbar snackbar;

    /**
     * 弹出地址选择
     */
    private void showConnectDialog(final String msg) {
        if (DialogUtils.dialogSSL) {
            if (Constant.isSll) {
                Constant.isSll = false;
                DialogUtils.insertDialog().dialogCenterComm(context, context.getString(R.string.kindly_reminder),
                        context.getString(R.string.sslguoqi), true, new OnDialogSureListener() {
                            @Override
                            public void onDialogSureListener() {
                                showHttpIP(msg);
                            }
                        });
            }
        } else {
            showHttpIP(msg);
        }

    }


    private void showHttpIP(String msg) {
        loginBottomDialog = new LoginBottomDialog(this, msg);
        loginBottomDialog.show();
        loginBottomDialog.setClicklistener(new LoginBottomDialog.ClickListenerInterface() {
            @Override
            public void scan() {
                int permissionCheck = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.CAMERA);
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.CAMERA}, 3);
                    snackbar = SnackBarUtil.show(LoginActivity.this, "获取相机信息说明：", "用于扫描二维码");
                } else {
                    //选择扫码输入服务器地址
                    loginBottomDialog.dismiss();
                    Intent intent = new Intent(LoginActivity.this, ConnectSettingActivity.class);
                    intent.putExtra("isScan", true);
                    startActivity(intent);
                }


            }

            @Override
            public void input() {
                //手动输入地址
                loginBottomDialog.dismiss();
                Intent intent = new Intent(LoginActivity.this, ConnectSettingActivity.class);
                startActivity(intent);

            }
        });
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    /**
     * 登陆成功
     */
    @Override
    public void loginSuccess() {

        //记住密码
        boolean remember_password = PreferencesHelper.getBooleanData("remember_password");
        if (remember_password) {
            PreferencesHelper.saveData("user_password", password_view.getText().toString());
        } else {
            PreferencesHelper.saveData("user_password", "");
        }

        sharedPrefs.edit().putString(Constant.LOGIN_NAME, getText(username_view)).apply();

        //判断是否为上一个用户的账号，如果不是清除用户拍摄的H5图片
        String loginName = sharedPrefs.getString(Constant.LAST_LOGIN_NAME, "");
        String lastAddress = sharedPrefs.getString(Constant.LAST_ADDRESS, "");
        if (!TextUtils.isEmpty(loginName) && !TextUtils.isEmpty(lastAddress)) {
            if (loginName.equals(getText(username_view)) && lastAddress.equals(sharedPrefs.getString(Constant.BASE_ADDRESS_URL, ""))) {
                //是上一个环境的同一个账户

            } else {

                //否则删除上一个人员的工作图片和数据库信息
                Utility.clearH5ImageData(this);
                List<Record> list = DBManager.getDBManager(this).getRecords(IMAGE.TABLE_NAME, null);
                DBManager.getDBManager(this).deleteRecords(list);
                //标注删除上一个人的H5缓存数据
                sharedPrefs.edit().putBoolean(Constant.CLEAR_LOCAL_STORAGE, true).apply();
            }
        }


        String de = "{\"sLon\":\"000.00\", \"sLon\":\"00.00\", \"Position\":\"暂未定位成功\"}";
        sharedPrefs.edit().putString(Constant.LON_LAT_DESC, de).apply();
        Utility.startLoginActivityForH5Home(this);
        hideLoading();
        finish();
    }

    //接口加载失败，弹出提示框
    @Override
    public void connentError(Throwable e) {
        showConnectDialog(context.getString(R.string.msg_connect_error));
        Log.e("HttpLoggingSSL", "数据异常--->" + e.getMessage() + "--" + (e instanceof SSLHandshakeException));
    }

    @Override
    public void sysSettingsInfoSuccess(SysSettingsInfoBean settingsInfoBean) {
        if (settingsInfoBean != null) {

            PreferencesHelper.saveData("isOkGetSysInfo", "true");

            Log.e("shuchang", "保存settingsInfoBean------>");
            UserHelper.saveSysSettingsInfoBean(settingsInfoBean);

            String pwd_mode = UserHelper.getSysSettingsValueBycode("PWD_LOGIN_MODE");
            //1(账号登录)2(短信登录)3(账号登录或短信可选登录)
            if (TextUtils.equals(pwd_mode, "1")) {
                loginWay = 1;

                rl_password.setVisibility(View.VISIBLE);
                rl_username.setVisibility(View.VISIBLE);
                ll_remember_password.setVisibility(View.VISIBLE);

                rl_phone.setVisibility(View.GONE);
                rl_sms_code.setVisibility(View.GONE);

                ll_login_way_layout.setVisibility(View.GONE);
            } else if ("2".equals(pwd_mode)) {
                loginWay = 2;

                rl_password.setVisibility(View.GONE);
                rl_username.setVisibility(View.GONE);
                ll_remember_password.setVisibility(View.GONE);

                rl_phone.setVisibility(View.VISIBLE);
                rl_sms_code.setVisibility(View.VISIBLE);

                ll_login_way_layout.setVisibility(View.GONE);
            } else {
                ll_login_way_layout.setVisibility(View.VISIBLE);
            }


            //忘记密码
            //SYS_PC
            //PWD_FORGET
            //0(否)1(是)
            PWD_FORGET = UserHelper.getSysSettingsValueBycode("PWD_FORGET");
            if ("0".equals(PWD_FORGET)) {
                tv_forget_pwd.setVisibility(View.GONE);
            } else {
                tv_forget_pwd.setVisibility(View.VISIBLE);
            }

            //是否显示记住密码
            IS_OPEN_REMEMBER_PASSWORD = UserHelper.getSysSettingsValueBycode("IS_OPEN_REMEMBER_PASSWORD");
            if ("0".equals(IS_OPEN_REMEMBER_PASSWORD)) {
                password_view.setText("");
                hook_checkbox.setVisibility(View.GONE);
                tv_remember_password.setVisibility(View.GONE);
            } else {
                hook_checkbox.setVisibility(View.VISIBLE);
                tv_remember_password.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void sysSettingsInfoFail() {
    }


    //获取通用协议内容
    @Override
    public void agreementContent(AgreementBean recordsBean) {
        //Log.e("1111", new Gson().toJson(recordsBean));
        PreferencesHelper.saveData(recordsBean);
        setAgreement();
    }

    //通用协议版本号与个人的协议不一致
    @Override
    public void AgreementDiffer() {

        Intent intent = new Intent(LoginActivity.this, AgreementActivity.class);
        intent.putExtra("agreement_flag", 1);
        startActivityForResult(intent, 5043);


    }

    @Override
    public void getXiYouSSOSettingSuccess(boolean flag) {
        if (flag) {

        } else {
            //账号密码
            findViewById(R.id.login_btn_sso).setVisibility(View.GONE);
            findViewById(R.id.login_btn).setVisibility(View.VISIBLE);
            findViewById(R.id.rl_password).setVisibility(View.VISIBLE);
            findViewById(R.id.rl_username).setVisibility(View.VISIBLE);

            findViewById(R.id.ll_login_lang).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void checkBuUnamepwdSuccess(String username) {
        //去登录
        if (loginWay == 1) {
            boolean xueditPwd = StringUtils.isPwdPartten(getText(password_view), mPattern);
            if (xueditPwd) {
                int[] pwd_lens = StringUtils.CommaSeparatedStringToIntArray(UserHelper.getSysSettingsValueBycode("PWD_LEN"));
                if (pwd_lens == null) {
                    presenter.login(TextUtils.isEmpty(username) ? getText(username_view) : username, getText(password_view), autiType, "");
                } else {
                    if (getText(password_view).length() < pwd_lens[0] || getText(password_view).length() > pwd_lens[1]) {
                        presenter.login(TextUtils.isEmpty(username) ? getText(username_view) : username, getText(password_view), autiType, "");

                        //  showEditPwdDialog("WEAK_PWD", TextUtils.isEmpty(username) ? getText(username_view) : username, "0");
                    } else {
                        presenter.login(TextUtils.isEmpty(username) ? getText(username_view) : username, getText(password_view), autiType, "");
                    }
                }
            } else {
                showEditPwdDialog("WEAK_PWD", TextUtils.isEmpty(username) ? getText(username_view) : username, "0");
            }
        }

    }

    @Override
    public void checkBuUnamepwdFailure(String code, String username) {
        showEditPwdDialog(code, username, "0");
    }

    @Override
    public void getTipsSuccess(String pattern) {
        Log.e("shuchang", "pattern---->" + pattern);
        this.mPattern = pattern;
    }

    @Override
    public void updatePwdSuccess() {
        if (editPwdDialog != null) {
            editPwdDialog.dismiss();
        }
        login_sms_code.setText("");
        password_view.setText("");
        ToastUtils.showShort(this, getResources().getString(R.string.change_success));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginBottomDialog != null && loginBottomDialog.isShowing()) {
            loginBottomDialog.dismiss();
        }
        Log.e("onDestroy", "onDestroy");
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 取消倒计时
        }
    }

    private int perType = 0;

    private void applyPermissions(int type) {
        perType = type;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            // 检查该权限是否已经获取
//            int i = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsLocation[0]);
//            int l = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsLocation[1]);
//            int m = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsStore[0]);
//            int n = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsInternet[3]);
//            int o = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsInternet[0]);
//            int p = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsInternet[1]);
//            int q = ContextCompat.checkSelfPermission(getApplicationContext(), permissionsInternet[2]);
//
//            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//            if (i != PackageManager.PERMISSION_GRANTED || l != PackageManager.PERMISSION_GRANTED || m != PackageManager.PERMISSION_GRANTED ||
//                    n != PackageManager.PERMISSION_GRANTED || o != PackageManager.PERMISSION_GRANTED || p != PackageManager.PERMISSION_GRANTED
//                    || q != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                startRequestPermission();
//                isApplyPermissions = true;
//            } else {
//                isApplyPermissions = false;
//                if (type == 0) {
//                    loginApp();
//                } else {
//                    Intent intent = new Intent();
//                    intent.setClass(context, LinkWebActivity.class);
//                    startActivityForResult(intent, 9784);
//                }
//            }
//        }

        if (type == 0) {
            loginApp();
        } else {
            Intent intent = new Intent();
            intent.setClass(context, LinkWebActivity.class);
            startActivityForResult(intent, 9784);
        }


    }

    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissionsLocation, 321);
        SnackBarUtil.show(this, "获取位置信息说明：", "用于定位工程师的位置");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 321:
                boolean allGranted = true;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        allGranted = false;
                        break;
                    }
                }

                ActivityCompat.requestPermissions(this, permissionsStore, 322);
                SnackBarUtil.show(this, "访问您设备上的照片、媒体内容和文件说明：", "用于存储个人用户信息");

//                if (allGranted) {
//                    // 所有权限被授予，执行登录逻辑
//                } else {
//                    // 部分或全部权限被拒绝，需要进一步提示用户或者处理逻辑
//                    // 可以选择让用户手动去设置中开启权限或者引导用户完成下一步操作
//                }
                break;
            case 322:
                ActivityCompat.requestPermissions(this, permissionsInternet, 323);
                SnackBarUtil.show(this, "读取通话状态和移动网络信息说明：", "用于判断当前的网络环境");
                break;
            case 323:
                if (perType == 0) {
                    loginApp();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(context, LinkWebActivity.class);
                    startActivityForResult(intent, 9784);
                }
                break;
            case 3://相机权限
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_scan_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AppManager.getAppManager().finishAllActivity();
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5043) {
            if (data != null) {
                int result = data.getIntExtra("Agreement_result", 0);
                if (result == 0) {
                    sharedPrefs.edit().putBoolean(Constant.LOOK_AGREEMENT, true).apply();
//                String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
//                if (Constant.APP_NAME_LINK.equals(appName)) {
//                    presenter.getUserInfo(UserHelper.getToken(),"");
//                }else {
//                    loginApp();
//                }
                } else {
                    sharedPrefs.edit().putBoolean(Constant.LOOK_AGREEMENT, false).apply();
                }
            }
        } else if (requestCode == 9784) {
            if (data != null && !loginCount) {
                loginCount = true;
                String token = data.getStringExtra("token");
                showLoading();
                presenter.getUserInfo(token, "");
            }
        }
    }

    private boolean loginCount;
    private CountDownTimer countDownTimer;

    private void startCountDownTimer(long millisInFuture, long countDownInterval) {
        countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_send_sms.setText(getResources().getString(R.string.again_get) + "(" + millisUntilFinished / 1000 + "S)");
            }

            @Override
            public void onFinish() {
                tv_send_sms.setEnabled(true);
                tv_send_sms.setText(getResources().getString(R.string.get_sms));
                tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
            }
        }.start();
    }


    private String getPhoneCode() {
        String phonecode = getText(login_phone) + "&" + getText(login_sms_code);
        return AESUtil.encryptAESExpand(phonecode);
    }


    // 清除 X5 内核的缓存
    public void clearX5Cache() {
        // 清除 WebView 缓存
        Log.e("111缓存", "111");
        QbSdk.clearAllWebViewCache(getApplicationContext(), true);
        // 清除 WebStorage 缓存
        WebStorage.getInstance().deleteAllData();
        // 清除 WebIconDatabase 缓存
        WebIconDatabase.getInstance().removeAllIcons();
        // 清除 Cookie
        CookieSyncManager.createInstance(getApplicationContext());
        CookieSyncManager.getInstance().startSync();
        CookieManager.getInstance().removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    public void loginSuccessSuccess(String token) {
        String keyUser = SharedPrefUtils.getInstance(context).getString("key_user_id", "");
        if (!TextUtils.equals(keyUser, token)) {
            clearX5Cache();
        }
    }
}